package com.cloud.shuiyu.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author rjw
 * <p>Description:   </p>
 * @ClassName PaymentService
 * @time 2021/7/17 10:20
 */

@Service
public class PaymentService {
    /**
     * 正常访问
     * @param id
     * @return
     */
    public String paymentinfo_OK(Integer id){
        return "线程池"+Thread.currentThread().getName()+"  paymentInfo_OK,id:"+id+"\t"+"哈哈";
    }

    /**
     * 模拟异常
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentinfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")  //表示这个方法的执行在3秒之内就是正常的，否则会走fallback
    })
    public String paymentinfo_TimeOut(Integer id){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //int a=10/0;

        return "线程池"+Thread.currentThread().getName()+"  paymentInfo_TimeOut,id:"+id+"\t"+"哈哈,耗时3秒钟";
    }

    /**
     * 这个是兜底的方法（服务降级），上面的出现问题，走这个
     * @param id
     * @return
     */
    public String paymentinfo_TimeOutHandler(Integer id){
        //走这里，会用Hystrix里面的线程池
        return "线程池"+Thread.currentThread().getName()+"  系统繁忙，请稍后再试,id:"+id+"\t"+"兜底了";
    }




    //==========服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期，10秒
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")// 在一定时间段内，失败率达到多少后跳闸
    } )
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if(id<0){
            throw new RuntimeException("***id 不能为负数");
        }
        String number= IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号："+number;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能为负数，请稍后再试，~~  id :"+id;
    }




}
